import { getDateDiff } from "../../../util/util"

const app = getApp()
// page/component/post.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    info: {
      type: Object,
      value: {}
    },
    actions: {
      type: Array,
      value: []
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    timeDiff: '',
    imgWidth: '600rpx',
    imgHeight: '360rpx',
  },

  /**
   * 组件的方法列表
   */
  methods: {
    previewImage(e) {
      const index = e.target.dataset.index
      wx.previewImage({
        urls: this.data.info.medias,
        current: this.data.info.medias[index],
      })
    },
    actionTap(e) {
      const index = e.target.dataset.index
      this.data.actions[index].cb(this.data.info)
    },
    go2userDetail(e) {
      wx.navigateTo({
        url: '/packageHome/pages/user-detail/index?openid=' + this.data.info.openid,
      })
    },
    go2detail(e) {
      const pages =  getCurrentPages()
      const current = pages[pages.length - 1]
      const detailPath = '/packageHome/pages/post-detail/index'
      ('/' + current.route) !== detailPath && wx.navigateTo({
        url: detailPath,
        success: (res) => {
          res.eventChannel.emit('init', { value: this.data.info })
        },
      })
    },
  },
  observers: {
    info(v) {
      if (v.medias.length === 1) {
        wx.getImageInfo({
          src: v.medias[0],
        })
        .then(res => {
          const { height, width } = res
          const h = height * app.globalData.pxRatio
          const w = width * app.globalData.pxRatio
          const ratio = w / h
          let imgH, imgW
          if (h <= 360 && w <= 600) {
            imgH = h
            imgW = w
          } else if (ratio > 1.6 ) {
            imgW = 600
            imgH = 600 / ratio
          } else {
            imgH = 360
            imgW = 360 * ratio
          }
          this.setData({
            imgWidth: imgW + 'rpx',
            imgHeight: imgH + 'rpx'
          })
        })
        .catch(e => console.error('get image info error in post: ' + v.medias[0]))
      }
    },
    "info.topTime": function(v) {
      this.setData({
        timeDiff: getDateDiff(v)
      })
    }
  }
})
